/**
 * User: alesj
 * Date: 2005.6.6
 * Time: 11:28:49
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.newsfeed.web.form;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alesj.newsfeed.web.object.FileUploadBean;
import com.generalynx.common.constants.WebConst;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class FileUploadController extends SimpleFormController {

    protected ModelAndView onSubmit(
        HttpServletRequest request,
        HttpServletResponse response,
        Object command,
        BindException errors) throws Exception {

        if (request instanceof MultipartHttpServletRequest) {
            FileUploadBean file = (FileUploadBean)command;
            if (file.getFile() != null && file.getFile().length > 0) {
                HttpSession session = request.getSession(false);
                List<FileUploadBean> attachments = (List<FileUploadBean>)session.getAttribute(WebConst.ATTACHMENTS);
                if (attachments == null) {
                    attachments = new ArrayList<FileUploadBean>();
                    session.setAttribute(WebConst.ATTACHMENTS, attachments);
                }
                MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest)request;
                MultipartFile mf = mhsr.getFile("file");
                if (mf != null) {
                    file.setName(mf.getOriginalFilename());
                    attachments.add(file);
                }
            } else {
                logger.warn("Submiting empty file.");
            }
            return new ModelAndView(getSuccessView());
        } else {
            throw new IllegalArgumentException("Request should be of Multipart instance!");
        }
    }

    protected void initBinder(
        HttpServletRequest request,
        ServletRequestDataBinder binder)
        throws ServletException {
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

}
